import { useContext, useEffect, useRef, useState } from 'react';
import { xhrPostJson } from '@/services';
import { DetailContext } from '@/biz-components/claim-items/components/DetailContext';
import {
  CommonTable,
  CellInput,
  CommonFilter,
  CommonFilterItem,
  FilterFunctions,
} from '@/biz-components/claim-items/components-v2';
import { useField } from '@formily/react';
import { Field } from '@formily/core/lib/models';
import ClaimItemsDataUtil from '@/biz-components/claim-items/ClaimItemsDataUtil';
import { plus } from '@ey-utils/utils/numberPrecision';
import { getAllTypesOfMetasByPageCode } from '@/biz-components/claim-items/components';
import * as CommonDataSource from '@/common-data-source';
import { SelectorExtraProps } from '@/biz-components/claim-items/components-v2/cell-input';

/**
 * @author DongPing
 * 2022/1/13 14:23
 *
 * 扣款池业务认领明细
 *
 * */

const PAGE_CODE = 'ClaimInfoA_Deduct_Business_IT_L';

export function DeductBusiness(props: {
  value: any[];
  onChange: (value: any[]) => void;

  shop: string;
  claimTarget: string;
  matchType: string;

  // 费用类型 扣款池业务认领查询认领明细用
  rbrsType: string;

  // 还本类型 扣款池业务认领查询明细用
  // 2022/2/28 15:25 废弃,改为从过滤器选择还本类型
  repymtType: string;
}) {
  const {
    value = [],
    onChange,
    shop = '',
    claimTarget = '',
    rbrsType,
    repymtType,
    matchType,
  } = props;

  const detailMode = useContext(DetailContext);
  const [metas, setMetas] = useState<any[]>([]);
  useEffect(function () {
    getAllTypesOfMetasByPageCode(PAGE_CODE).then((data) => {
      setMetas(data.tableColumnMetas);
    });
  }, []);

  const getFilterObjRef = useRef<() => any>(null);

  function queryData() {
    // 从过滤器获取还本类型的值
    let filter = getFilterObjRef.current ? getFilterObjRef.current() : {};
    const hb = filter.repymtType || '';
    const detailItemType = filter.dctnDetail || '';

    xhrPostJson('/asm/claimDetail/bizCutPaytList', {
      claimObject: claimTarget,
      companyCode: shop,
      matchNatur: matchType,
      rbrsType: rbrsType,
      // 还本类型
      repymtType: hb,
      dctnDetail: detailItemType,
    }).then((res: any) => {
      let data = res.result || [];
      data = data.filter((item: any) => {
        if (hb && item.repymtType !== hb) {
          return false;
        }
        if (detailItemType && item.dctnDetail !== detailItemType) {
          return false;
        }
        return true;
      });
      onChange(ClaimItemsDataUtil.setTempId(data));
    });
  }

  useEffect(
    function () {
      if (detailMode) return;
      queryData();
    },
    [shop, claimTarget, matchType, rbrsType, repymtType],
  );

  const hbOptions = CommonDataSource.dictionary.useDictionaryOptions('PPMT_TYPE');
  // http://jira.ecsphere.net:9080/browse/XYL-1457
  const [showHBLX, setShowHBLX] = useState(false);
  function onFilterChange() {
    if (getFilterObjRef.current) {
      const obj = getFilterObjRef.current();
      setShowHBLX(['DK01', 'DK02', 'DK03'].includes(obj.dctnDetail));
    }
    setTimeout(() => {
      queryData();
    }, 200);
  }

  const validateRef = useRef<() => boolean>(null);
  const field = useField<Field>();
  useEffect(function () {
    field.setValidator(() => {
      if (validateRef.current && validateRef.current()) {
        return null;
      } else {
        return { type: 'error', message: '认领信息填写有误' };
      }
    });
    return function () {
      field.setValidator(() => {});
    };
  }, []);

  const [detailOptions, setDetailOptions] = useState<Array<{ name: string; value: string }>>([]);
  useEffect(function () {
    // CommonDataSource.dictionary
    //   .queryAllChildren({ dictType: 'DCTN_BIZ_TYPE' })
    //   .then(setDetailOptions);
  }, []);

  return (
    <>
      {detailMode ? null : (
        <CommonFilter
          filterFunctionRef={{ current: null }}
          onChange={onFilterChange}
          metaArr={metas.concat([
            {
              key: 'repymtType',
              label: '还本类型',
            },
          ])}
          getCurrentFilterObjectRef={getFilterObjRef}
        >
          <CommonFilterItem<string, SelectorExtraProps>
            name={'dctnDetail'}
            Component={[CellInput.Selector, { dataSource: detailOptions, showSearch: true }]}
            filterFunction={FilterFunctions.stringEqual}
          />
          {showHBLX ? (
            <CommonFilterItem<string, SelectorExtraProps>
              name={'repymtType'}
              Component={[CellInput.Selector, { dataSource: hbOptions }]}
              filterFunction={FilterFunctions.stringEqual}
            />
          ) : null}
        </CommonFilter>
      )}
      <CommonTable
        pageCode={PAGE_CODE}
        metaArr={metas}
        value={value}
        onChange={onChange}
        detailMode={detailMode}
        claimItemsInvalid={true}
        validateFunctionRef={validateRef}
        checkOperation
        onCheckChange={(record, checked) => {
          for (const item of value) {
            if (null === record || item === record) {
              item.__checked = checked;
              if (checked) {
                /**
                 * http://jira.ecsphere.net:9080/browse/XYL-1733
                 * 涉及资金的业务单据认领方式，勾选对应的业务单据后，本次认领金额默认取单据金额，不可编辑
                 * */
                if (
                  (item.dctnDetail === 'DK01' && item.repymtType === 'D03') ||
                  item.dctnDetail === 'DK02'
                ) {
                  item.thisClaimAmt = item.billAmt;
                } else {
                  item.thisClaimAmt = item.unClaimedAmt;
                }
              } else {
                item.thisClaimAmt = '';
              }
            }
          }
          onChange([...value]);
        }}
        columnsOptionArr={[
          {
            name: 'thisClaimAmt',
            component: [CellInput.NumberInput, {}],
            validator: (v, r) => {
              if (!r.__checked) return true;
              let nThis = Number(r.thisClaimAmt);
              let notClaim = Number(r.unClaimedAmt);
              return nThis > 0 && nThis <= notClaim;
            },
            disabled: (record: any) => {
              return (
                (record.dctnDetail === 'DK01' && record.repymtType === 'D03') ||
                record.dctnDetail === 'DK02'
              );
            },
          },
        ]}
      />
    </>
  );
}
DeductBusiness.calcAmount = calcAmount;
/**
 * 计算认领明细总和
 * */
function calcAmount(data: any[] = []) {
  let sum = 0;
  try {
    for (const item of data) {
      if (!item.__checked) continue;
      let n = Number(item.thisClaimAmt);
      if (isNaN(n)) continue;
      sum = plus(sum, n);
    }
  } catch (err) {}
  return sum;
}
DeductBusiness.getCheckedData = function (data: any[] = []) {
  return ClaimItemsDataUtil.removeTempId(data.filter((item) => !!item.__checked));
};
